package org.lstt.ExcelReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Poi解析Excel工具类
 * 
 * @author tluo
 *
 */
public class PoiExcelUtil {
	private final static StringCellReader stringCellRead = new StringCellReader();
	private final static ObjectCellReader objectCellRead = new ObjectCellReader();

	public static List<Object[]> readExcelObject(InputStream is, String fileName) {
		return readExcelObject(is, fileName, null);
	}

	public static List<Object[]> readExcelObject(InputStream is,
			String fileName, Integer initArrlenth) {
		return readExcel(is, fileName, initArrlenth, 0, null, objectCellRead);
	}

	public static List<Object[]> readExcelString(InputStream is, String fileName) {
		return readExcelString(is, fileName, null);
	}

	public static List<Object[]> readExcelString(InputStream is,
			String fileName, Integer initArrlenth) {
		return readExcel(is, fileName, initArrlenth, 0, null, stringCellRead);
	}

	public static List<Object[]> readExcel(InputStream is, String fileName,
			Integer initArrlenth, int sheetIndex, List<Integer> skipRows,
			CellReader<?> cellRead) {
		List<Object[]> resList = new ArrayList<Object[]>();
		if (null == is) {
			return resList;
		}
		try {
			Workbook workbook = getWorkbook(is, fileName);
			Sheet sheet = workbook.getSheetAt(sheetIndex);
			if (null == sheet) {
				throw new RuntimeException("sheet is null.");
			}
			int rowNumber = 0;
			boolean isSpecifiedSize = false;
			if (null != initArrlenth && initArrlenth > 0) {
				isSpecifiedSize = true;
			}
			rowfor: for (Iterator<Row> rows = sheet.iterator(); rows.hasNext(); rowNumber++) {
				if (null != skipRows && skipRows.contains(rowNumber)) {
					continue rowfor;
				}
				Row row = rows.next();
				if (null == row || row.getLastCellNum() < 0) {
					resList.add(new Object[0]);
					continue rowfor;
				}
				int size = isSpecifiedSize ? initArrlenth : row
						.getLastCellNum();
				Object[] rowArr = new Object[size];
				for (int i = 0; i < size; i++) {
					Cell cell = row.getCell(i);
					rowArr[i] = cellRead.readCell(cell);
				}
				resList.add(rowArr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resList;
	}

	public static Workbook getWorkbook(InputStream is, String fileName)
			throws IOException {
		if (fileName.endsWith(".xlsx")) {
			return new XSSFWorkbook(is);
		} else if (fileName.endsWith(".xls")) {
			return new HSSFWorkbook(is);
		}
		return null;
	}

}
